package com.gator.mybatis.configuration;

import com.gator.mybatis.sqlsesson.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ResourceBundle;

/**
 * @Authror PABLO
 * @Date 2022/4/26 21:28
 * @Desc 配置类  保存接口映射器和sql语句
 */
public class Configuration {


    public static final ResourceBundle sqlMappings;
    
    //解析配置文件SQL语句
    static {
        sqlMappings = ResourceBundle.getBundle("sql");
    }


    /**
     * @Description: 根据clazz动态代理获取代理对象
     * @Author: PABLO
     * @Date: 2022/4/26 21:45
     * @Params:
     * @Return:
     **/
    public <T> T getMapper(Class<T>  clazz, SqlSession sqlSession) {
        return  (T)Proxy.newProxyInstance(
                clazz.getClassLoader(),
                new Class[]{clazz}, new MyInvocation(sqlSession) {
                });
    }


}

class MyInvocation implements InvocationHandler{

    private SqlSession sqlSession;

    public MyInvocation(SqlSession sqlSession){
        this.sqlSession = sqlSession;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        String statementId = method.//被代理的方法
                getDeclaringClass().//namespace
                        getName() + "." +
                method.getName();//methodName
        return sqlSession.selectOne(statementId, args[0]);
    }
}

